package com.example.commonlib.httplib;

import android.content.Context;

import com.example.commonlib.httplib.utils.StringDefaultAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Create by xjs
 * _______date : 17/8/2
 * _______description:无头部信息
 */
public class RetrofitUtils {

    private static RetrofitUtils retrofitManager;

    private OkHttpClient okHttpClient;

    private Retrofit retrofit;

    //全局上下文
    public Context context;

    private RetrofitUtils(Context context) {
        this.context = context;
    }

    /**
     * 同步锁，解决多线程初始化
     *
     * @param context
     * @return
     */
    public static RetrofitUtils getInstance(Context context) {
        if (retrofitManager == null) {
            synchronized (RetrofitUtils.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitUtils(context);
                }
            }
        }
        return retrofitManager;
    }
    /**
     * 创建retrofit
     *
     * @param service
     * @param <T>
     * @return
     */
    public <T> T getApiService(Class<T> service) {
        return retrofit.create(service);
    }


    public void initRetrofit(String baseUrl) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(String.class, new StringDefaultAdapter())
                .setLenient()
                .create();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }

    public RetrofitUtils initOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        okHttpClient = builder.connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)  //重连
                .build();
        return this;
    }
}
